<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
      layout:decorate="~{layout/default}">
<head>
    <meta charset="UTF-8">
    <title>帝一流</title>
    <link th:href="@{/static/plugin/bootstrap-table/bootstrap-table.css}" type="text/css" rel="stylesheet">
</head>
<body>
<div layout:fragment="cm-flex" class="cm-flex">
    <div class="cm-breadcrumb-container">
        <ol class="breadcrumb">
            <li><a href="#">系统管理</a></li>
            <li class="active">用户管理</li>
        </ol>
    </div>
    <form id="cm-search" action="index.html" method="get">
        <input type="search" name="q" autocomplete="off" placeholder="Search...">
    </form>
</div>
<div layout:fragment="content" class="container-fluid">
    <div class="panel panel-default">
        <div class="panel-body auto-height">
            <div class="search-block" id="search-block">
                <form action="#" class="form-group form-horizontal">
                    <div class="row">
                        <div class="col-sm-6 col-md-4">
                            <input type="text" class="form-control" placeholder="登录名/用户名" id="search"
                                   data-toggle="completer" data-suggest="true" th:attr="data-source=${#request.getAttribute('names')}">
                        </div>
                        <div class="col-sm-2 col-sm-offset-4 col-md-1 col-md-offset-7">
                            <button type="button" class="btn btn-primary btn-block" id="doSearch">查询</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="btn-group" role="group" id="toolbar">
                <button type="button" class="btn btn-default" id="addUser"><i class="fa fa-fw fa-plus"></i></button>
                <button type="button" class="btn btn-default" id="editUser"><i class="fa fa-fw fa-pencil"></i></button>
                <button type="button" class="btn btn-default" id="delUser"><i class="fa fa-fw fa-trash-o"></i></button>
            </div>
            <table id="userTable"></table>
        </div>
    </div>
</div>
<div layout:fragment="myJs">
    <div id="userModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h5 class="modal-title" id="userModalTitle">
                        添加用户
                    </h5>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" role="form" id="userForm">
                        <input type="hidden" id="id" name="id">
                        <div class="form-group">
                            <label for="username" class="col-sm-2 control-label">登录名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="username" name="username" placeholder="登录名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="name" class="col-sm-2 control-label">用户名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="name" name="name" placeholder="用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="tel" class="col-sm-2 control-label">电话</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="tel" name="tel" placeholder="电话">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="email" class="col-sm-2 control-label">邮箱</label>
                            <div class="col-sm-10">
                                <input type="email" class="form-control" id="email" name="email" placeholder="邮箱">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="selRole" class="col-sm-2 control-label">角色</label>
                            <div class="col-sm-10">
                                <select id="selRole" name="roleId" data-placeholder="选择角色 ..."
                                        class="form-control chosen-select">
                                    <option value=""></option>
                                    <option th:each="role:${#request.getAttribute('roles')}" th:value="${role.id}"
                                            th:text="${role.name}"></option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="expireTime" class="col-sm-2 control-label">过期时间</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="expireTime" name="expireTimeStr"
                                       placeholder="过期时间">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveUser">保存</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>
    <script th:src="@{/static/plugin/bootstrap-table/bootstrap-table.js}"></script>
    <script th:src="@{/static/plugin/bootstrap-table/bootstrap-table-locale-all.js}"></script>
    <script th:inline="javascript">
        $(function () {
            var autoHeight = $("div.auto-height").height();
            var rowHeight = $('#search-block').height();
            var tableHeight = autoHeight - rowHeight;

            var $table = $('#userTable');
            $table.bootstrapTable({
                // 条纹
                striped: true,
                height: tableHeight,
                toolbar: '#toolbar',
                pagination: true,
                paginationLoop: false,
                sidePagination: 'server',
                url: /*[[@{/sys/userList}]]*/,
                method: 'post',
                contentType: "application/x-www-form-urlencoded",
                dataField: "data",
                queryParamsType: '',
                queryParams: function queryParams(params) {
                    var param = {
                        pageNo: params.pageNumber,
                        pageSize: params.pageSize,
                        search: $('#search').val()
                    };
                    return param;
                },
                formatLoadingMessage: function () {
                    return "正在加载数据中，请稍候……"
                },
                formatShowingRows: function (a, b, c) {
                    return "第 " + a + " / " + b + " 条，共 " + c + " 条 ";
                },
                formatRecordsPerPage: function (a) {
                    return "每页 " + a;
                },
                columns: [
                    {
                        field: '',
                        checkbox: true
                    },
                    {
                        field: 'username',
                        title: '登录名'
                    },
                    {
                        field: 'name',
                        title: '姓名'
                    },
                    {
                        field: 'roles',
                        title: '角色',
                        formatter: function (value, row, index) {
                            if (value.length > 0) {
                                return value[0]['name'];
                            }

                            return '';
                        }
                    },
                    {
                        field: '',
                        title: '机构'
                    },
                    {
                        field: 'tel',
                        title: '手机'
                    },
                    {
                        field: 'lastLoginTime',
                        title: '登录时间'
                    },
                    {
                        field: 'createTime',
                        title: '创建时间',
                        formatter: function (value, row, index) {
                            var str = '';
                            if (value) {
                                str = value.substr(0, 10);
                            }

                            return '<span style="cursor: default" title="' + value + '">' + str + '</span>';
                        }
                    },
                    {
                        field: 'status',
                        title: '状态',
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (1 == value) {
                                return '<span class="sf-switch-on" style="display: inline-block;width: 16px;height: 16px;background-size: 16px 16px;"></span>';
                            }

                            return '<span class="sf-switch-off" style="display: inline-block;width: 16px;height: 16px;background-size: 16px 16px;"></span>';
                        }
                    },
                    {
                        field: '',
                        title: '重置密码',
                        align: 'center',
                        formatter: function (value, row, index) {
                            return '<a href="javascript:void(0);" onclick="resetPwd(this);" data-id="' + row.id + '" title="重置密码"><span class="sf-lock" style="display: inline-block;width: 16px;height: 16px;background-size: 16px 16px;"></span></a>';
                        }
                    }
                ]
            });

            $('#doSearch').on('click', function () {
                $table.bootstrapTable("refresh");
            });

            $('#addUser').on('click', function () {
                $('#selRole').chosen("destroy");
                $('#userForm')[0].reset();

                $('#userModalTitle').html('添加用户');
                $('#id').val('');
                document.getElementById('username').readOnly = false;
                $('#userModal').modal('show');
                $('#selRole').chosen();

                // 设置默认过期时间
                var expire = new Date();
                expire.setFullYear(expire.getFullYear() + 1);
                expire.setDate(expire.getDate() - 1);
                laydate.render({
                    elem: '#expireTime'
                    , type: 'datetime'
                    , value: expire
                });
            });

            $('#saveUser').on('click', function () {
                var param = $('#userForm').serialize();
                $.ajax({
                    type: $('#id').val() == '' ? 'post' : 'put',
                    url: /*[[@{/sys/user}]]*/,
                    data: param,
                    dataType: "json",
                    success: function (result) {
                        if (result == 1) {
                            $('#userModal').modal('hide');
                            $('#userTable').bootstrapTable('refresh');

                            alertTip('success', '保存成功');
                        } else {
                            alertTip('error', '保存失败');
                        }
                    }
                });
            });

            $('#editUser').on('click', function () {
                var users = $table.bootstrapTable('getSelections');
                if (users.length != 1) {
                    swal("请选择一个用户进行修改!");

                    return;
                }

                // 重置表单
                $('#selRole').chosen("destroy");
                $('#userForm')[0].reset();

                var user = users[0];
                $('#id').val(user['id']);
                $('#username').val(user['username']);
                $('#name').val(user['name']);
                $('#tel').val(user['tel']);
                $('#email').val(user['email']);

                $('#userModalTitle').html('修改角色');
                document.getElementById('username').readOnly = true;
                $('#userModal').modal('show');

                var role = user['roles'][0];
                if (role) {
                    var roleId = role.id;
                    var options = document.getElementById('selRole').options;
                    for (var i = 0; i < options.length; i++) {
                        var o = options[i];
                        if (o.value == roleId) {
                            o.selected = true;
                        }
                    }
                }

                $('#selRole').chosen();
                laydate.render({
                    elem: '#expireTime'
                    , type: 'datetime'
                    , value: user['expireTime']
                });
            });

            $('#delUser').on('click', function () {
                var users = $table.bootstrapTable('getSelections');
                if (users.length < 1) {
                    swal("请至少选择一个用户进行删除!");

                    return;
                }
                // 提示
                swal({
                        title: "确定删除选中用户?",
                        text: "删除后将无法恢复",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#e67e22",
                        confirmButtonText: "删除",
                        closeOnConfirm: true
                    },
                    function () {
                        var idArr = [];
                        for (var i = 0; i < users.length; i++) {
                            idArr[i] = users[i]['id'];
                        }
                        $.ajax({
                            type: 'delete',
                            url: /*[[@{/sys/user}]]*/,
                            contentType: "application/json;charset=utf-8",
                            data: JSON.stringify(idArr),
                            dataType: "json",
                            success: function (result) {
                                if (result == 1) {
                                    $('#userModal').modal('hide');
                                    $('#userTable').bootstrapTable('refresh');

                                    alertTip('success', '删除成功');
                                } else {
                                    alertTip('error', '删除失败');
                                }
                            }
                        });
                    });
            });
        });

        function resetPwd(a) {
            var id = $(a).data('id');
            // 提示
            swal({
                    title: "重置用户密码?",
                    text: "重置后原密码将无法使用",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#e67e22",
                    confirmButtonText: "重置",
                    closeOnConfirm: true
                },
                function () {
                    var path = /*[[@{/sys/userPwd/}]]*/;
                    $.ajax({
                        type: 'put',
                        url: path + id,
                        dataType: "json",
                        success: function (result) {
                            if (result == 1) {
                                alertTip('success', '重置密码成功');
                            } else {
                                alertTip('error', '重置密码失败');
                            }
                        }
                    });
                });
        };
    </script>
</div>
</body>
</html>